<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>jest-practice | Zachary&#39;s blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="A quick overview to Jest, a test framework for Node.js. This guide targets Jest v20. Mrm and jest-codemods are for single-command Jest installation and easy migration from other frameworks.">
<meta property="og:type" content="article">
<meta property="og:title" content="jest-practice">
<meta property="og:url" content="http://dontcry2013.github.io/2019/12/05/jest-practice/index.html">
<meta property="og:site_name" content="Zachary&#39;s blog">
<meta property="og:description" content="A quick overview to Jest, a test framework for Node.js. This guide targets Jest v20. Mrm and jest-codemods are for single-command Jest installation and easy migration from other frameworks.">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2019-12-12T03:29:04.170Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="jest-practice">
<meta name="twitter:description" content="A quick overview to Jest, a test framework for Node.js. This guide targets Jest v20. Mrm and jest-codemods are for single-command Jest installation and easy migration from other frameworks.">
  
    <link rel="alternative" href="/atom.xml" title="Zachary&#39;s blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/img/favicon.png">
  
  <link rel="stylesheet" href="/css/style.css">
  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e907b20dbb2f8d2eb9402532629ec091";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</head>
</html>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/img/litten.png" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Zachary</a></h1>
		</hgroup>

		
		<p class="header-subtitle">No pain, no gain</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
						<div class="icon-wrap icon-me hide" data-idx="3">
							<div class="user"></div>
							<div class="shoulder"></div>
						</div>
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>Menu</li>
						<li>Tags</li>
						
						<li>Links</li>
						
						
						<li>About</li>
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/">homepage</a></li>
				        
							<li><a href="/archives">archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
								<a class="github" target="_blank" href="https://github.com/dontcry2013" title="github">github</a>
					        
								<a class="weibo" target="_blank" href="http://weibo.com/u/2278451152" title="weibo">weibo</a>
					        
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						<a href="/tags/android/" style="font-size: 14px;">Android</a> <a href="/tags/apache/" style="font-size: 10px;">Apache</a> <a href="/tags/c/" style="font-size: 14px;">C</a> <a href="/tags/css/" style="font-size: 10px;">CSS</a> <a href="/tags/closure/" style="font-size: 10px;">Closure</a> <a href="/tags/command/" style="font-size: 12px;">Command</a> <a href="/tags/es2017/" style="font-size: 14px;">ES2017</a> <a href="/tags/es5/" style="font-size: 18px;">ES5</a> <a href="/tags/es6/" style="font-size: 18px;">ES6</a> <a href="/tags/example/" style="font-size: 10px;">Example</a> <a href="/tags/fiddler/" style="font-size: 10px;">Fiddler</a> <a href="/tags/git/" style="font-size: 12px;">Git</a> <a href="/tags/github/" style="font-size: 14px;">GitHub</a> <a href="/tags/html/" style="font-size: 10px;">HTML</a> <a href="/tags/http/" style="font-size: 10px;">HTTP</a> <a href="/tags/hexo/" style="font-size: 12px;">Hexo</a> <a href="/tags/issue/" style="font-size: 10px;">Issue</a> <a href="/tags/jni/" style="font-size: 10px;">JNI</a> <a href="/tags/java/" style="font-size: 14px;">Java</a> <a href="/tags/mandarin/" style="font-size: 16px;">Mandarin</a> <a href="/tags/markdown/" style="font-size: 10px;">Markdown</a> <a href="/tags/mongodb/" style="font-size: 10px;">MongoDB</a> <a href="/tags/ndk/" style="font-size: 10px;">NDK</a> <a href="/tags/node-js/" style="font-size: 14px;">Node.js</a> <a href="/tags/objective-c/" style="font-size: 10px;">Objective-C</a> <a href="/tags/oracle/" style="font-size: 12px;">Oracle</a> <a href="/tags/php/" style="font-size: 10px;">PHP</a> <a href="/tags/prototype/" style="font-size: 12px;">Prototype</a> <a href="/tags/proxy/" style="font-size: 10px;">Proxy</a> <a href="/tags/react-native/" style="font-size: 10px;">React Native</a> <a href="/tags/sql/" style="font-size: 10px;">SQL</a> <a href="/tags/sublime/" style="font-size: 10px;">Sublime</a> <a href="/tags/todo/" style="font-size: 10px;">TODO</a> <a href="/tags/travis/" style="font-size: 10px;">Travis</a> <a href="/tags/ubuntu/" style="font-size: 10px;">Ubuntu</a> <a href="/tags/webview/" style="font-size: 10px;">Webview</a> <a href="/tags/jquery/" style="font-size: 12px;">jQuery</a> <a href="/tags/prototype/" style="font-size: 10px;">prototype</a> <a href="/tags/碎碎念/" style="font-size: 20px;">碎碎念</a> <a href="/tags/英语/" style="font-size: 10px;">英语</a>
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.thirdtea.com/">三号茶馆</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.jianshu.com/users/c2f3ff613436/latest_articles">猫哥学前班</a>
			        
			        </div>
				</section>
				

				
				
				<section class="switch-part switch-part4">
				
					<div id="js-aboutme">我是谁，我从哪里来，我到哪里去？我就是我，是颜色不一样的吃货…</div>
				</section>
				
			</div>
		</div>
	</header>				
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Zachary</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
			
				<img lazy-src="/img/litten.png" class="js-avatar">
			
			</div>
			<hgroup>
			  <h1 class="header-author">Zachary</h1>
			</hgroup>
			
			<p class="header-subtitle">No pain, no gain</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">homepage</a></li>
		        
					<li><a href="/archives">archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="https://github.com/dontcry2013" title="github">github</a>
			        
						<a class="weibo" target="_blank" href="http://weibo.com/u/2278451152" title="weibo">weibo</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap"><article id="post-jest-practice" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2019/12/05/jest-practice/" class="article-date">
  	<time datetime="2019-12-05T11:27:47.000Z" itemprop="datePublished">2019-12-05</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      jest-practice
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>A quick overview to Jest, a test framework for Node.js. This guide targets Jest v20.</p>
<p><em><a href="https://github.com/sapegin/mrm-tasks/tree/master/packages/mrm-task-jest" target="_blank" rel="noopener">Mrm</a> and <a href="https://github.com/skovhus/jest-codemods" target="_blank" rel="noopener">jest-codemods</a> are for single-command Jest installation and easy migration from other frameworks.</em><br><a id="more"></a></p>
<!-- toc -->
<ul>
<li><a href="#test-structure">Test structure</a></li>
<li><a href="#matchers">Matchers</a><ul>
<li><a href="#basic-matchers">Basic matchers</a></li>
<li><a href="#truthiness">Truthiness</a></li>
<li><a href="#numbers">Numbers</a></li>
<li><a href="#strings">Strings</a></li>
<li><a href="#arrays">Arrays</a></li>
<li><a href="#objects">Objects</a></li>
<li><a href="#exceptions">Exceptions</a></li>
<li><a href="#snapshots">Snapshots</a></li>
<li><a href="#mock-functions">Mock functions</a></li>
<li><a href="#misc">Misc</a></li>
<li><a href="#promise-matchers-jest-20">Promise matchers (Jest 20+)</a></li>
</ul>
</li>
<li><a href="#async-tests">Async tests</a><ul>
<li><a href="#asyncawait">async/await</a></li>
<li><a href="#promises">Promises</a></li>
<li><a href="#done-callback">done() callback</a></li>
</ul>
</li>
<li><a href="#mocks">Mocks</a><ul>
<li><a href="#mock-functions-1">Mock functions</a></li>
<li><a href="#mock-modules-using-jestmock-method">Mock modules using <code>jest.mock</code> method</a></li>
<li><a href="#mock-modules-using-a-mock-file">Mock modules using a mock file</a></li>
<li><a href="#mock-object-methods">Mock object methods</a></li>
<li><a href="#mock-getters-and-setters-jest-2210">Mock getters and setters (Jest 22.1.0+)</a></li>
<li><a href="#mock-getters-and-setters">Mock getters and setters</a></li>
<li><a href="#clearing-and-restoring-mocks">Clearing and restoring mocks</a></li>
<li><a href="#accessing-the-original-module-when-using-mocks">Accessing the original module when using mocks</a></li>
<li><a href="#timer-mocks">Timer mocks</a></li>
</ul>
</li>
<li><a href="#data-driven-tests-jest-23">Data-driven tests (Jest 23+)</a></li>
<li><a href="#skipping-tests">Skipping tests</a></li>
<li><a href="#testing-modules-with-side-effects">Testing modules with side effects</a></li>
<li><a href="#usage-with-babel-and-typescript">Usage with Babel and TypeScript</a></li>
<li><a href="#resources">Resources</a></li>
<li><a href="#you-may-also-like">You may also like</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#author-and-license">Author and license</a></li>
</ul>
<!-- tocstop -->
<h2 id="Test-structure"><a href="#Test-structure" class="headerlink" title="Test structure"></a>Test structure</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">describe(<span class="string">'makePoniesPink'</span>, () =&gt; &#123;</span><br><span class="line">  beforeAll(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">/* Runs before all tests */</span></span><br><span class="line">  &#125;)</span><br><span class="line">  afterAll(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">/* Runs after all tests */</span></span><br><span class="line">  &#125;)</span><br><span class="line">  beforeEach(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">/* Runs before each test */</span></span><br><span class="line">  &#125;)</span><br><span class="line">  afterEach(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">/* Runs after each test */</span></span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  test(<span class="string">'make each pony pink'</span>, () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> actual = fn([<span class="string">'Alice'</span>, <span class="string">'Bob'</span>, <span class="string">'Eve'</span>])</span><br><span class="line">    expect(actual).toEqual([<span class="string">'Pink Alice'</span>, <span class="string">'Pink Bob'</span>, <span class="string">'Pink Eve'</span>])</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="Matchers"><a href="#Matchers" class="headerlink" title="Matchers"></a>Matchers</h2><p><a href="http://jestjs.io/docs/en/using-matchers" target="_blank" rel="noopener">Using matchers</a>, <a href="https://facebook.github.io/jest/docs/expect.html" target="_blank" rel="noopener">matchers docs</a></p>
<h3 id="Basic-matchers"><a href="#Basic-matchers" class="headerlink" title="Basic matchers"></a>Basic matchers</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">expect(<span class="number">42</span>).toBe(<span class="number">42</span>) <span class="comment">// Strict equality (===)</span></span><br><span class="line">expect(<span class="number">42</span>).not.toBe(<span class="number">3</span>) <span class="comment">// Strict equality (!==)</span></span><br><span class="line">expect([<span class="number">1</span>, <span class="number">2</span>]).toEqual([<span class="number">1</span>, <span class="number">2</span>]) <span class="comment">// Deep equality</span></span><br><span class="line">expect(&#123; <span class="attr">a</span>: <span class="literal">undefined</span>, <span class="attr">b</span>: <span class="number">2</span> &#125;).toEqual(&#123; <span class="attr">b</span>: <span class="number">2</span> &#125;) <span class="comment">// Deep equality</span></span><br><span class="line">expect(&#123; <span class="attr">a</span>: <span class="literal">undefined</span>, <span class="attr">b</span>: <span class="number">2</span> &#125;).not.toStrictEqual(&#123; <span class="attr">b</span>: <span class="number">2</span> &#125;) <span class="comment">// Strict equality (Jest 23+)</span></span><br></pre></td></tr></table></figure>
<h3 id="Truthiness"><a href="#Truthiness" class="headerlink" title="Truthiness"></a>Truthiness</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Matches anything that an if statement treats as true (not false, 0, '', null, undefined, NaN)</span></span><br><span class="line">expect(<span class="string">'foo'</span>).toBeTruthy()</span><br><span class="line"><span class="comment">// Matches anything that an if statement treats as false (false, 0, '', null, undefined, NaN)</span></span><br><span class="line">expect(<span class="string">''</span>).toBeFalsy()</span><br><span class="line"><span class="comment">// Matches only null</span></span><br><span class="line">expect(<span class="literal">null</span>).toBeNull()</span><br><span class="line"><span class="comment">// Matches only undefined</span></span><br><span class="line">expect(<span class="literal">undefined</span>).toBeUndefined()</span><br><span class="line"><span class="comment">// The opposite of toBeUndefined</span></span><br><span class="line">expect(<span class="number">7</span>).toBeDefined()</span><br></pre></td></tr></table></figure>
<h3 id="Numbers"><a href="#Numbers" class="headerlink" title="Numbers"></a>Numbers</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">expect(<span class="number">2</span>).toBeGreaterThan(<span class="number">1</span>)</span><br><span class="line">expect(<span class="number">1</span>).toBeGreaterThanOrEqual(<span class="number">1</span>)</span><br><span class="line">expect(<span class="number">1</span>).toBeLessThan(<span class="number">2</span>)</span><br><span class="line">expect(<span class="number">1</span>).toBeLessThanOrEqual(<span class="number">1</span>)</span><br><span class="line">expect(<span class="number">0.2</span> + <span class="number">0.1</span>).toBeCloseTo(<span class="number">0.3</span>, <span class="number">5</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Strings"><a href="#Strings" class="headerlink" title="Strings"></a>Strings</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">expect(<span class="string">'long string'</span>).toMatch(<span class="string">'str'</span>)</span><br><span class="line">expect(<span class="string">'coffee'</span>).toMatch(<span class="regexp">/ff/</span>)</span><br><span class="line">expect(<span class="string">'pizza'</span>).not.toMatch(<span class="string">'coffee'</span>)</span><br><span class="line">expect([<span class="string">'pizza'</span>, <span class="string">'coffee'</span>]).toEqual([expect.stringContaining(<span class="string">'zz'</span>), expect.stringMatching(<span class="regexp">/ff/</span>)])</span><br></pre></td></tr></table></figure>
<h3 id="Arrays"><a href="#Arrays" class="headerlink" title="Arrays"></a>Arrays</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">expect([<span class="string">'Alice'</span>, <span class="string">'Bob'</span>, <span class="string">'Eve'</span>]).toHaveLength(<span class="number">3</span>)</span><br><span class="line">expect([<span class="string">'Alice'</span>, <span class="string">'Bob'</span>, <span class="string">'Eve'</span>]).toContain(<span class="string">'Alice'</span>)</span><br><span class="line">expect([&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;, &#123; <span class="attr">a</span>: <span class="number">2</span> &#125;]).toContainEqual(&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;)</span><br><span class="line">expect([<span class="string">'Alice'</span>, <span class="string">'Bob'</span>, <span class="string">'Eve'</span>]).toEqual(expect.arrayContaining([<span class="string">'Alice'</span>, <span class="string">'Bob'</span>]))</span><br></pre></td></tr></table></figure>
<h3 id="Objects"><a href="#Objects" class="headerlink" title="Objects"></a>Objects</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">expect(&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;).toHaveProperty(<span class="string">'a'</span>)</span><br><span class="line">expect(&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;).toHaveProperty(<span class="string">'a'</span>, <span class="number">1</span>)</span><br><span class="line">expect(&#123; <span class="attr">a</span>: &#123; <span class="attr">b</span>: <span class="number">1</span> &#125; &#125;).toHaveProperty(<span class="string">'a.b'</span>)</span><br><span class="line">expect(&#123; <span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">2</span> &#125;).toMatchObject(&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;)</span><br><span class="line">expect(&#123; <span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">2</span> &#125;).toMatchObject(&#123;</span><br><span class="line">  a: expect.any(<span class="built_in">Number</span>),</span><br><span class="line">  b: expect.any(<span class="built_in">Number</span>)</span><br><span class="line">&#125;)</span><br><span class="line">expect([&#123; <span class="attr">a</span>: <span class="number">1</span> &#125;, &#123; <span class="attr">b</span>: <span class="number">2</span> &#125;]).toEqual([</span><br><span class="line">  expect.objectContaining(&#123; <span class="attr">a</span>: expect.any(<span class="built_in">Number</span>) &#125;),</span><br><span class="line">  expect.anything()</span><br><span class="line">])</span><br></pre></td></tr></table></figure>
<h3 id="Exceptions"><a href="#Exceptions" class="headerlink" title="Exceptions"></a>Exceptions</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// const fn = () =&gt; &#123; throw new Error('Out of cheese!') &#125;</span></span><br><span class="line">expect(fn).toThrow()</span><br><span class="line">expect(fn).toThrow(<span class="string">'Out of cheese'</span>)</span><br><span class="line">expect(fn).toThrowErrorMatchingSnapshot()</span><br></pre></td></tr></table></figure>
<details><br>  <summary>Aliases</summary><br><br>- <code>toThrowError</code> → <code>toThrow</code><br>  </details>

<h3 id="Snapshots"><a href="#Snapshots" class="headerlink" title="Snapshots"></a>Snapshots</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">expect(node).toMatchSnapshot()</span><br><span class="line"><span class="comment">// Jest 23+</span></span><br><span class="line">expect(user).toMatchSnapshot(&#123;</span><br><span class="line">  date: expect.any(<span class="built_in">Date</span>)</span><br><span class="line">&#125;)</span><br><span class="line">expect(user).toMatchInlineSnapshot()</span><br></pre></td></tr></table></figure>
<h3 id="Mock-functions"><a href="#Mock-functions" class="headerlink" title="Mock functions"></a>Mock functions</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// const fn = jest.fn()</span></span><br><span class="line"><span class="comment">// const fn = jest.fn().mockName('Unicorn') -- named mock, Jest 22+</span></span><br><span class="line">expect(fn).toBeCalled() <span class="comment">// Function was called</span></span><br><span class="line">expect(fn).not.toBeCalled() <span class="comment">// Function was *not* called</span></span><br><span class="line">expect(fn).toHaveBeenCalledTimes(<span class="number">1</span>) <span class="comment">// Function was called only once</span></span><br><span class="line">expect(fn).toBeCalledWith(arg1, arg2) <span class="comment">// Any of calls was with these arguments</span></span><br><span class="line">expect(fn).toHaveBeenLastCalledWith(arg1, arg2) <span class="comment">// Last call was with these arguments</span></span><br><span class="line">expect(fn).toHaveBeenNthCalledWith(args) <span class="comment">// Nth call was with these arguments (Jest 23+)</span></span><br><span class="line">expect(fn).toHaveReturnedTimes(<span class="number">2</span>) <span class="comment">// Function was returned without throwing an error (Jest 23+)</span></span><br><span class="line">expect(fn).toHaveReturnedWith(value) <span class="comment">// Function returned a value (Jest 23+)</span></span><br><span class="line">expect(fn).toHaveLastReturnedWith(value) <span class="comment">// Last function call returned a value (Jest 23+)</span></span><br><span class="line">expect(fn).toHaveNthReturnedWith(value) <span class="comment">// Nth function call returned a value (Jest 23+)</span></span><br><span class="line">expect(fn.mock.calls).toEqual([[<span class="string">'first'</span>, <span class="string">'call'</span>, <span class="string">'args'</span>], [<span class="string">'second'</span>, <span class="string">'call'</span>, <span class="string">'args'</span>]]) <span class="comment">// Multiple calls</span></span><br><span class="line">expect(fn.mock.calls[<span class="number">0</span>][<span class="number">0</span>]).toBe(<span class="number">2</span>) <span class="comment">// fn.mock.calls[0][0] — the first argument of the first call</span></span><br></pre></td></tr></table></figure>
<details><br>  <summary>Aliases</summary><br><br>- <code>toBeCalled</code> → <code>toHaveBeenCalled</code><br>- <code>toBeCalledWith</code> → <code>toHaveBeenCalledWith</code><br>- <code>lastCalledWith</code> → <code>toHaveBeenLastCalledWith</code><br>- <code>nthCalledWith</code> → <code>toHaveBeenNthCalledWith</code><br>- <code>toReturnTimes</code> → <code>toHaveReturnedTimes</code><br>- <code>toReturnWith</code> → <code>toHaveReturnedWith</code><br>- <code>lastReturnedWith</code> → <code>toHaveLastReturnedWith</code><br>- <code>nthReturnedWith</code> → <code>toHaveNthReturnedWith</code><br>  </details>

<h3 id="Misc"><a href="#Misc" class="headerlink" title="Misc"></a>Misc</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">expect(<span class="keyword">new</span> A()).toBeInstanceOf(A)</span><br><span class="line">expect(<span class="function"><span class="params">()</span> =&gt;</span> &#123;&#125;).toEqual(expect.any(<span class="built_in">Function</span>))</span><br><span class="line">expect(<span class="string">'pizza'</span>).toEqual(expect.anything())</span><br></pre></td></tr></table></figure>
<h3 id="Promise-matchers-Jest-20"><a href="#Promise-matchers-Jest-20" class="headerlink" title="Promise matchers (Jest 20+)"></a>Promise matchers (Jest 20+)</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'resolve to lemon'</span>, () =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">1</span>)</span><br><span class="line">  <span class="comment">// Make sure to add a return statement</span></span><br><span class="line">  <span class="keyword">return</span> expect(<span class="built_in">Promise</span>.resolve(<span class="string">'lemon'</span>)).resolves.toBe(<span class="string">'lemon'</span>)</span><br><span class="line">  <span class="comment">// return expect(Promise.reject('octopus')).rejects.toBeDefined();</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>Or with async/await:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'resolve to lemon'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">2</span>)</span><br><span class="line">  <span class="keyword">await</span> expect(<span class="built_in">Promise</span>.resolve(<span class="string">'lemon'</span>)).resolves.toBe(<span class="string">'lemon'</span>)</span><br><span class="line">  <span class="keyword">await</span> expect(<span class="built_in">Promise</span>.resolve(<span class="string">'lemon'</span>)).resolves.not.toBe(<span class="string">'octopus'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><a href="https://facebook.github.io/jest/docs/en/expect.html#resolves" target="_blank" rel="noopener">resolves docs</a></p>
<h2 id="Async-tests"><a href="#Async-tests" class="headerlink" title="Async tests"></a>Async tests</h2><p>See <a href="https://facebook.github.io/jest/docs/en/tutorial-async.html" target="_blank" rel="noopener">more examples</a> in Jest docs.</p>
<p>It’s a good practice to specify a number of expected assertions in async tests, so the test will fail if your assertions weren’t called at all.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'async test'</span>, () =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">3</span>) <span class="comment">// Exactly three assertions are called during a test</span></span><br><span class="line">  <span class="comment">// OR</span></span><br><span class="line">  expect.hasAssertions() <span class="comment">// At least one assertion is called during a test</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// Your async tests</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="async-await"><a href="#async-await" class="headerlink" title="async/await"></a>async/await</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'async test'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">1</span>)</span><br><span class="line">  <span class="keyword">const</span> result = <span class="keyword">await</span> runAsyncOperation()</span><br><span class="line">  expect(result).toBe(<span class="literal">true</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="Promises"><a href="#Promises" class="headerlink" title="Promises"></a>Promises</h3><p><em>Return</em> a Promise from your test:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'async test'</span>, () =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">1</span>)</span><br><span class="line">  <span class="keyword">return</span> runAsyncOperation().then(<span class="function"><span class="params">result</span> =&gt;</span> &#123;</span><br><span class="line">    expect(result).toBe(<span class="literal">true</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="done-callback"><a href="#done-callback" class="headerlink" title="done() callback"></a>done() callback</h3><p>Wrap your assertions in try/catch block, otherwise Jest will ignore failures:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'async test'</span>, done =&gt; &#123;</span><br><span class="line">  expect.assertions(<span class="number">1</span>)</span><br><span class="line">  runAsyncOperation()</span><br><span class="line">  setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> result = getAsyncOperationResult()</span><br><span class="line">      expect(result).toBe(<span class="literal">true</span>)</span><br><span class="line">      done()</span><br><span class="line">    &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">      done.fail(err)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="Mocks"><a href="#Mocks" class="headerlink" title="Mocks"></a>Mocks</h2><h3 id="Mock-functions-1"><a href="#Mock-functions-1" class="headerlink" title="Mock functions"></a>Mock functions</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'call the callback'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> callback = jest.fn()</span><br><span class="line">  fn(callback)</span><br><span class="line">  expect(callback).toBeCalled()</span><br><span class="line">  expect(callback.mock.calls[<span class="number">0</span>][<span class="number">1</span>].baz).toBe(<span class="string">'pizza'</span>) <span class="comment">// Second argument of the first call</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>You can also use snapshots:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'call the callback'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> callback = jest.fn().mockName(<span class="string">'Unicorn'</span>) <span class="comment">// mockName is available in Jest 22+</span></span><br><span class="line">  fn(callback)</span><br><span class="line">  expect(callback).toMatchSnapshot()</span><br><span class="line">  <span class="comment">// -&gt;</span></span><br><span class="line">  <span class="comment">// [MockFunction Unicorn] &#123;</span></span><br><span class="line">  <span class="comment">//   "calls": Array [</span></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>And pass an implementation to <code>jest.fn</code> function:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> callback = jest.fn(<span class="function"><span class="params">()</span> =&gt;</span> <span class="literal">true</span>)</span><br></pre></td></tr></table></figure>
<p><a href="https://facebook.github.io/jest/docs/mock-function-api.html" target="_blank" rel="noopener">Mock functions docs</a></p>
<h3 id="Mock-modules-using-jest-mock-method"><a href="#Mock-modules-using-jest-mock-method" class="headerlink" title="Mock modules using jest.mock method"></a>Mock modules using <code>jest.mock</code> method</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">jest.mock(<span class="string">'lodash/memoize'</span>, () =&gt; <span class="function"><span class="params">a</span> =&gt;</span> a) <span class="comment">// The original lodash/memoize should exist</span></span><br><span class="line">jest.mock(<span class="string">'lodash/memoize'</span>, () =&gt; <span class="function"><span class="params">a</span> =&gt;</span> a, &#123; <span class="attr">virtual</span>: <span class="literal">true</span> &#125;) <span class="comment">// The original lodash/memoize isn’t required</span></span><br></pre></td></tr></table></figure>
<p><a href="https://facebook.github.io/jest/docs/jest-object.html#jestmockmodulename-factory-options" target="_blank" rel="noopener">jest.mock docs</a></p>
<blockquote>
<p>Note: When using <code>babel-jest</code>, calls to <code>jest.mock</code> will automatically be hoisted to the top of the code block. Use <code>jest.doMock</code> if you want to explicitly avoid this behavior.</p>
</blockquote>
<h3 id="Mock-modules-using-a-mock-file"><a href="#Mock-modules-using-a-mock-file" class="headerlink" title="Mock modules using a mock file"></a>Mock modules using a mock file</h3><ol>
<li><p>Create a file like <code>__mocks__/lodash/memoize.js</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="params">a</span> =&gt;</span> a</span><br></pre></td></tr></table></figure>
</li>
<li><p>Add to your test:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jest.mock(<span class="string">'lodash/memoize'</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<blockquote>
<p>Note: When using <code>babel-jest</code>, calls to <code>jest.mock</code> will automatically be hoisted to the top of the code block. Use <code>jest.doMock</code> if you want to explicitly avoid this behavior.</p>
</blockquote>
<p><a href="https://facebook.github.io/jest/docs/manual-mocks.html" target="_blank" rel="noopener">Manual mocks docs</a></p>
<h3 id="Mock-object-methods"><a href="#Mock-object-methods" class="headerlink" title="Mock object methods"></a>Mock object methods</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> spy = jest.spyOn(ajax, <span class="string">'request'</span>).mockImplementation(<span class="function"><span class="params">()</span> =&gt;</span> <span class="built_in">Promise</span>.resolve(&#123; <span class="attr">success</span>: <span class="literal">true</span> &#125;))</span><br><span class="line">expect(spy).toHaveBeenCalled()</span><br><span class="line">spy.mockRestore()</span><br></pre></td></tr></table></figure>
<h3 id="Mock-getters-and-setters-Jest-22-1-0"><a href="#Mock-getters-and-setters-Jest-22-1-0" class="headerlink" title="Mock getters and setters (Jest 22.1.0+)"></a>Mock getters and setters (Jest 22.1.0+)</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> location = &#123;&#125;</span><br><span class="line"><span class="keyword">const</span> getTitle = jest.spyOn(location, <span class="string">'title'</span>, <span class="string">'get'</span>).mockImplementation(<span class="function"><span class="params">()</span> =&gt;</span> <span class="string">'pizza'</span>)</span><br><span class="line"><span class="keyword">const</span> setTitle = jest.spyOn(location, <span class="string">'title'</span>, <span class="string">'set'</span>).mockImplementation(<span class="function"><span class="params">()</span> =&gt;</span> &#123;&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="Mock-getters-and-setters"><a href="#Mock-getters-and-setters" class="headerlink" title="Mock getters and setters"></a>Mock getters and setters</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> getTitle = jest.fn(<span class="function"><span class="params">()</span> =&gt;</span> <span class="string">'pizza'</span>)</span><br><span class="line"><span class="keyword">const</span> setTitle = jest.fn()</span><br><span class="line"><span class="keyword">const</span> location = &#123;&#125;</span><br><span class="line"><span class="built_in">Object</span>.defineProperty(location, <span class="string">'title'</span>, &#123;</span><br><span class="line">  <span class="keyword">get</span>: getTitle,</span><br><span class="line">  <span class="keyword">set</span>: setTitle</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="Clearing-and-restoring-mocks"><a href="#Clearing-and-restoring-mocks" class="headerlink" title="Clearing and restoring mocks"></a>Clearing and restoring mocks</h3><p>For one mock:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fn.mockClear() <span class="comment">// Clears mock usage date (fn.mock.calls, fn.mock.instances)</span></span><br><span class="line">fn.mockReset() <span class="comment">// Clears and removes any mocked return values or implementations</span></span><br><span class="line">fn.mockRestore() <span class="comment">// Resets and restores the initial implementation</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>Note: <code>mockRestore</code> works only with mocks created by <code>jest.spyOn</code>.</p>
</blockquote>
<p>For all mocks:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">jest.clearAllMocks()</span><br><span class="line">jest.resetAllMocks()</span><br><span class="line">jest.restoreAllMocks()</span><br></pre></td></tr></table></figure>
<h3 id="Accessing-the-original-module-when-using-mocks"><a href="#Accessing-the-original-module-when-using-mocks" class="headerlink" title="Accessing the original module when using mocks"></a>Accessing the original module when using mocks</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">jest.mock(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>) <span class="comment">// Mocked module</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>.requireActual(<span class="string">'fs'</span>) <span class="comment">// Original module</span></span><br></pre></td></tr></table></figure>
<h3 id="Timer-mocks"><a href="#Timer-mocks" class="headerlink" title="Timer mocks"></a>Timer mocks</h3><p>Write synchronous test for code that uses native timer functions (<code>setTimeout</code>, <code>setInterval</code>, <code>clearTimeout</code>, <code>clearInterval</code>).</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Enable fake timers</span></span><br><span class="line">jest.useFakeTimers()</span><br><span class="line"></span><br><span class="line">test(<span class="string">'kill the time'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> callback = jest.fn()</span><br><span class="line">  <span class="comment">// Run some code that uses setTimeout or setInterval</span></span><br><span class="line">  <span class="keyword">const</span> actual = someFunctionThatUseTimers(callback)</span><br><span class="line">  <span class="comment">// Fast-forward until all timers have been executed</span></span><br><span class="line">  jest.runAllTimers()</span><br><span class="line">  <span class="comment">// Check the results synchronously</span></span><br><span class="line">  expect(callback).toHaveBeenCalledTimes(<span class="number">1</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>Use <a href="https://jestjs.io/docs/en/timer-mocks#run-pending-timers" target="_blank" rel="noopener">jest.runOnlyPendingTimers()</a> for special cases.</p>
<p>Or adjust timers by time with <a href="https://jestjs.io/docs/en/timer-mocks#advance-timers-by-time" target="_blank" rel="noopener">advanceTimersByTime()</a>.</p>
<h2 id="Data-driven-tests-Jest-23"><a href="#Data-driven-tests-Jest-23" class="headerlink" title="Data-driven tests (Jest 23+)"></a>Data-driven tests (Jest 23+)</h2><p>Run the same test with different data:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">test.each([[<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>], [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">2</span>, <span class="number">1</span>, <span class="number">3</span>]])(<span class="string">'.add(%s, %s)'</span>, (a, b, expected) =&gt; &#123;</span><br><span class="line">  expect(a + b).toBe(expected)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>Or the same using template literals:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">test.each<span class="string">`</span></span><br><span class="line"><span class="string">  a    | b    | expected</span></span><br><span class="line"><span class="string">  <span class="subst">$&#123;<span class="number">1</span>&#125;</span> | <span class="subst">$&#123;<span class="number">1</span>&#125;</span> | <span class="subst">$&#123;<span class="number">2</span>&#125;</span></span></span><br><span class="line"><span class="string">  <span class="subst">$&#123;<span class="number">1</span>&#125;</span> | <span class="subst">$&#123;<span class="number">2</span>&#125;</span> | <span class="subst">$&#123;<span class="number">3</span>&#125;</span></span></span><br><span class="line"><span class="string">  <span class="subst">$&#123;<span class="number">2</span>&#125;</span> | <span class="subst">$&#123;<span class="number">1</span>&#125;</span> | <span class="subst">$&#123;<span class="number">3</span>&#125;</span></span></span><br><span class="line"><span class="string">`</span>(<span class="string">'returns $expected when $a is added $b'</span>, (&#123; a, b, expected &#125;) =&gt; &#123;</span><br><span class="line">  expect(a + b).toBe(expected)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><a href="https://jestjs.io/docs/en/api.html#testeachtable-name-fn-timeout" target="_blank" rel="noopener">test.each() docs</a></p>
<h2 id="Skipping-tests"><a href="#Skipping-tests" class="headerlink" title="Skipping tests"></a>Skipping tests</h2><p>Don’t run these tests:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">describe.skip(<span class="string">'makePoniesPink'</span>...</span><br><span class="line">tests.skip(<span class="string">'make each pony pink'</span>...</span><br></pre></td></tr></table></figure>
<p>Run only these tests:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">describe.only(<span class="string">'makePoniesPink'</span>...</span><br><span class="line">tests.only(<span class="string">'make each pony pink'</span>...</span><br></pre></td></tr></table></figure>
<h2 id="Testing-modules-with-side-effects"><a href="#Testing-modules-with-side-effects" class="headerlink" title="Testing modules with side effects"></a>Testing modules with side effects</h2><p>Node.js and Jest will cache modules you <code>require</code>. To test modules with side effects you’ll need to reset the module registry between tests:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> modulePath = <span class="string">'../module-to-test'</span></span><br><span class="line"></span><br><span class="line">afterEach(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  jest.resetModules()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">test(<span class="string">'first test'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="comment">// Prepare conditions for the first test</span></span><br><span class="line">  <span class="keyword">const</span> result = <span class="built_in">require</span>(modulePath)</span><br><span class="line">  expect(result).toMatchSnapshot()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">test(<span class="string">'second text'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="comment">// Prepare conditions for the second test</span></span><br><span class="line">  <span class="keyword">const</span> fn = <span class="function"><span class="params">()</span> =&gt;</span> <span class="built_in">require</span>(modulePath)</span><br><span class="line">  expect(fn).toThrow()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="Usage-with-Babel-and-TypeScript"><a href="#Usage-with-Babel-and-TypeScript" class="headerlink" title="Usage with Babel and TypeScript"></a>Usage with Babel and TypeScript</h2><p>Add <a href="https://github.com/facebook/jest/tree/master/packages/babel-jest" target="_blank" rel="noopener">babel-jest</a> or <a href="https://github.com/kulshekhar/ts-jest" target="_blank" rel="noopener">ts-jest</a>. Check their docs for installation instructions.</p>
<h2 id="Resources"><a href="#Resources" class="headerlink" title="Resources"></a>Resources</h2><ul>
<li><a href="https://facebook.github.io/jest/" target="_blank" rel="noopener">Jest site</a></li>
<li><a href="http://blog.sapegin.me/all/react-jest" target="_blank" rel="noopener">Testing React components with Jest and Enzyme</a> by Artem Sapegin</li>
<li><a href="https://react-testing-examples.com/" target="_blank" rel="noopener">React Testing Examples</a></li>
<li><a href="https://youtu.be/59Ndb3YkLKA" target="_blank" rel="noopener">Testing React Applications</a> by Max Stoiber</li>
<li><a href="https://blog.kentcdodds.com/effective-snapshot-testing-e0d1a2c28eca" target="_blank" rel="noopener">Effective Snapshot Testing</a> by Kent C. Dodds</li>
<li><a href="https://medium.com/@kentcdodds/migrating-to-jest-881f75366e7e#.pc4s5ut6z" target="_blank" rel="noopener">Migrating to Jest</a> by Kent C. Dodds</li>
<li><a href="http://browniefed.com/blog/migrating-ava-to-jest/" target="_blank" rel="noopener">Migrating AVA to Jest</a> by Jason Brown</li>
<li><a href="https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest" target="_blank" rel="noopener">How to Test React and MobX with Jest</a> by Will Stern</li>
<li><a href="https://medium.com/@sapegin/testing-react-intl-components-with-jest-and-enzyme-f9d43d9c923e" target="_blank" rel="noopener">Testing React Intl components with Jest and Enzyme</a> by Artem Sapegin</li>
<li><a href="https://medium.com/@stipsan/testing-with-jest-15-awesome-tips-and-tricks-42150ec4c262" target="_blank" rel="noopener">Testing with Jest: 15 Awesome Tips and Tricks</a> by Stian Didriksen</li>
<li>Taking Advantage of Jest Matchers by Ben McCormick: <a href="https://benmccormick.org/2017/08/15/jest-matchers-1/" target="_blank" rel="noopener">Part 1</a>, <a href="https://benmccormick.org/2017/09/04/jest-matchers-2/" target="_blank" rel="noopener">Part 2</a></li>
</ul>
<hr>
<h2 id="You-may-also-like"><a href="#You-may-also-like" class="headerlink" title="You may also like"></a>You may also like</h2><ul>
<li><a href="https://github.com/sapegin/react-components" target="_blank" rel="noopener">Opinionated list of React components</a></li>
</ul>
<h2 id="Contributing"><a href="#Contributing" class="headerlink" title="Contributing"></a>Contributing</h2><p>Improvements are welcome! Open an issue or send a pull request.</p>
<h2 id="Author-and-license"><a href="#Author-and-license" class="headerlink" title="Author and license"></a>Author and license</h2><p><a href="http://sapegin.me/" target="_blank" rel="noopener">Artem Sapegin</a>, a frontend engineer at <a href="https://omio.com/" target="_blank" rel="noopener">Omio</a> and the creator of <a href="https://react-styleguidist.js.org/" target="_blank" rel="noopener">React Styleguidist</a>. I also write about frontend at <a href="https://blog.sapegin.me/" target="_blank" rel="noopener">my blog</a>.</p>
<p>CC0 1.0 Universal license, see the included <a href="/License.md">License.md</a> file.</p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2019/12/05/docker/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption"><</strong>
      <div class="article-nav-title">
        
          Getting started with Docker
        
      </div>
    </a>
  
  
    <a href="/2019/12/02/github-code-block/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">Languages Supported by Github Flavored Markdown</div>
      <strong class="article-nav-caption">></strong>
    </a>
  
</nav>

  
</article>


<div class="share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">Share to: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
    <a class="jiathis_button_twitter"></a>
    <a class="jiathis_button_plus"></a> 
    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="jest-practice" data-title="jest-practice" data-url="http://dontcry2013.github.io/2019/12/05/jest-practice/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"true"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>




</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2019 Zachary
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>






<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  </div>
</body>
</html>